<?php

namespace Unl\HomologacionBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Unl\HomologacionBundle\Entity\Area;
use Unl\HomologacionBundle\Entity\Carrera;
use Unl\HomologacionBundle\Form\AreaType;
use Unl\HomologacionBundle\Form\CarreraType;

/**
 * Area controller.
 *
 * @Route("/area")
 */
class AreaController extends Controller {
    
    /**
     * Lists all Area entities.
     *
     * @Route("/", name="area")
     * @Template()
     */
    public function indexAction() {
        
        $sample = new Area();
        $sample->setNombre('');
        
        $searchForm = $this->createForm(new AreaType(), $sample);
        $request = $this->getRequest();
        $searchForm->bindRequest($request);

        $em = $this->getDoctrine()->getEntityManager();
        $entities = $em->getRepository('UnlHomologacionBundle:Area')->findByNombre($sample->getNombre());
        
        return array('entities' => $entities, 
                     'search_form' => $searchForm->createView());
    }

    /**
     * Finds and displays a Area entity.
     *
     * @Route("/{id}/show", name="area_show")
     * @Template()
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('UnlHomologacionBundle:Area')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se encuentra el Area.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity' => $entity,
            'delete_form' => $deleteForm->createView(),);
    }

    /**
     * Displays a form to create a new Area entity.
     *
     * @Route("/new", name="area_new")
     * @Template()
     */
    public function newAction() {
        $entity = new Area();
        $form = $this->createForm(new AreaType(), $entity);

        return array(
            'entity' => $entity,
            'edit_form' => $form->createView()
        );
    }

    /**
     * Creates a new Area entity.
     *
     * @Route("/create", name="area_create")
     * @Method("post")
     * @Template("UnlHomologacionBundle:Area:new.html.twig")
     */
    public function createAction() {
        $entity = new Area();
        $request = $this->getRequest();
        $form = $this->createForm(new AreaType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('area', array('descripcion' => $entity->__toString())));
        }

        return array(
            'entity' => $entity,
            'edit_form' => $form->createView()
        );
    }

    /**
     * Agrega carrera al Area actual
     *
     * @Route("/carreraAdd", name="carrera_add")
     * @Template("UnlHomologacionBundle:Area:edit.html.twig")
     */
    public function addCarreraAction() {
        $entity = $this->get('session')->get('area');
        if ($entity != NULL) {
            $carrera = new Carrera();
            $carrera->setUniversidad(null);
            $entity->addCarrera($carrera);
            $editForm = $this->createForm(new AreaType(), $entity);

            //$deleteForm = NULL;
            if ($entity->getId() != NULL) {
                $deleteForm = $this->createDeleteForm($entity->getId());
            }

            $request = $this->getRequest();
            $editForm->bindRequest($request);

            return array(
                'entity' => $entity,
                'edit_form' => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            );
        } else {
            return new \Symfony\Component\HttpFoundation\Response("NO SE ENCONTRO EL AREA");
        }
    }

    /**
     * Displays a form to edit an existing Area entity.
     *
     * @Route("/{id}/edit", name="area_edit")
     * @Template()
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('UnlHomologacionBundle:Area')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Area entity.');
        }

        $editForm = $this->createForm(new AreaType(), $entity);
        //$deleteForm = $this->createDeleteForm($id);
        $this->get('session')->set('area', $entity);

        return array(
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            //'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Area entity.
     *
     * @Route("/{id}/update", name="area_update")
     * @Method("post")
     * @Template("UnlHomologacionBundle:Area:edit.html.twig")
     */
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('UnlHomologacionBundle:Area')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Area entity.');
        }
        
       
        $originalCarreras =array();
        foreach ($entity->getCarreras() as $carrera) $originalCarreras[] = $carrera;
        

        $editForm = $this->createForm(new AreaType(), $entity);
        //$deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            
            
            // filtra $originalCarreras para evitar aquellas que ya no estan presentes
            foreach ($entity->getCarreras() as $carrera) {
                foreach ($originalCarreras as $key => $toDel) {
                    if ($toDel->getId() === $carrera->getId()) {
                        unset($originalCarreras[$key]);
                    }
                }
            }
            
            // Se quita la relacion entre carrera y area
            foreach ($originalCarreras as $carrera) {
                // remove the Task from the Tag
                $carrera->setArea(null); //->removeElement($task);
                $em->persist($carrera);
                //$em->remove($carrera);
            }
            
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('area', array('descripcion' => $entity->__toString())));
        }

        return array(
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            //'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Area entity.
     *
     * @Route("/{id}/delete", name="area_delete")
     * @Method("post")
     */
    public function deleteAction($id) {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('UnlHomologacionBundle:Area')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Area entity.');
            }

            $eliminar=$entity->__toString();
            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('area', array('eliminar'=> $eliminar)));
    }

    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

}


        //$searchForm = $this->createForm(new AreaType(), $sample);
        /*
        $searchForm = $this->createFormBuilder($sample)
                            ->add('nombre', 'text')->getForm();
         * 
         */
        //$entities = $em->getRepository('UnlHomologacionBundle:Area')->findByNombre($nombre);
